package com.gitee.liuzhi.demo.other;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author LiuZhi
 * @Date 2022/3/29 21:05
 * @Description 正确加锁方式
 */
@Slf4j
public class LockDemo {

    private static final Map<Integer, String> NAME_MAP = Maps.newConcurrentMap();

    private static final Lock LOCK = new ReentrantLock();

    private static final Integer ID = 1;

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new Thread(() -> System.out.println(select())).start();
        }

    }

    private static String select() {
        String name = selectFromRedis();
        if (StringUtils.isNotBlank(name)) {
            return name;
        }
        LOCK.lock();
        try {
            name = selectFromRedis();
            if (StringUtils.isBlank(name)) {
                name = selectFromMysql();
                NAME_MAP.put(ID, name);
            }
            return name;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        } finally {
            LOCK.unlock();
        }
    }

    /**
     * 从关系型数据库查数据
     */
    private static String selectFromMysql() {
        log.info("select from mysql");
        return "LiuZhi";
    }

    /**
     * 从缓存中查数据
     */
    private static String selectFromRedis() {
        log.info("select from redis");
        return NAME_MAP.get(ID);
    }

}
